package com.cloudkinto.controller.product;


import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.service.product.importVo.DistributeStockImportRes;
import com.cloudkinto.service.product.vo.rack.*;
import com.cloudkinto.extentity.StockFlowingDto;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.product.ProductStockRackService;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cloudkinto.base.BaseController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hua`
 * @since 2022-12-21
 */
@RestController
@Api(tags = "库位库存模块")
@RequestMapping("/api/admin/ProductStockRack")
public class ProductStockRackController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(ProductStockRackController.class);

    @Autowired
    private ProductStockRackService service;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit();
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId));
    }

    @UserSessionRequired
    @GetMapping("/updateStockInit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rackId", value = "库位ID"),
            @ApiImplicitParam(name = "store", value = "发货区 配货区"),
            @ApiImplicitParam(name = "storageId", value = "仓库ID"),
            @ApiImplicitParam(name = "productId", value = "产品Id")
    })
    @ApiOperation(value = "分配库存/更新库存初始化", notes = "分配库存/更新库存初始化")
    public SingleResult updateStockInit(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String rackId = request.getParameter("rackId");
        String productId = request.getParameter("productId");
        String storageId = request.getParameter("storageId");
        String store = request.getParameter("store");


        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("rackId", rackId);
        map.put("store", store);
        map.put("productId", productId);
        map.put("storageId", storageId);
        return service.updateStockInit(map);
    }


    @UserSessionRequired
    @GetMapping("/getPostions")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storageId", value = "仓库ID"),
    })
    @ApiOperation(value = "获取库位", notes = "获取库位")
    public SingleResult getPostions(String storageId) {
        return SingleResult.success(service.getPostions(storageId));
    }


    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit();
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询库位库存（不分页）", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "sort", value = "排队方式 asc desc"),
            @ApiImplicitParam(name = "sortColumn", value = "排序列"),
            @ApiImplicitParam(name = "type", value = "1:只展示有库存的数据 0:展示所有数据  默认传1")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ProductStockRackRes.class))
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();
        String storageId = request.getParameter("storageId");
        Map<String, String> map = new HashMap<>();
        map.put("storageId", storageId);
        map.put("type", "1");//1:只展示有库存的数据 0:展示所有数据  默认传1
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "store", value = "发货区还是配货区"),
            @ApiImplicitParam(name = "keyword", value = "关键词"),
            @ApiImplicitParam(name = "sort", value = "排队方式 asc desc"),
            @ApiImplicitParam(name = "sortColumn", value = "排序列"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "type", value = "1:只展示有库存的数据 0:展示所有数据  默认传1")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ProductStockRackRes.class))
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String storageId = request.getParameter("storageId");
        String sort = request.getParameter("sort");
        String sortColumn = request.getParameter("sortColumn");
        String type = request.getParameter("type");
        String store = request.getParameter("store");


        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("keyword", keyword);
        map.put("store", store);
        map.put("current", current);
        map.put("sort", sort);
        map.put("sortColumn", sortColumn);
        map.put("pageSize", size);
        map.put("storageId", storageId);
        map.put("type", type);

        return service.getListPage(map);
    }


    @UserSessionRequired
    @GetMapping("/getStockByRackId")
    @ApiOperation(value = "库位一览查看详情（分页）", notes = "库位一览查看详情（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rackId", value = "库位id"),
            @ApiImplicitParam(name = "store", value = "发货区 0 ,配货区 1"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "keyword", value = "关键词"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),
            @ApiImplicitParam(name = "current", value = "当前页")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ProductStockDetailRes.class))
    public PageResult getStockByRackId(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String rackId = request.getParameter("rackId");
        String storageId = request.getParameter("storageId");
        String store = request.getParameter("store");


        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("storageId", storageId);
        map.put("store", store);

        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        map.put("rackId", rackId);

        return service.getStockByRackId(map);
    }


    @UserSessionRequired
    @GetMapping("/getStockList")
    @ApiOperation(value = "库位一览查看详情（分页）", notes = "库位一览查看详情（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rackId", value = "库位id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "keyword", value = "关键词"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),
            @ApiImplicitParam(name = "current", value = "当前页")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ProductStockDetailRes.class))
    public Object getStockList(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String rackId = request.getParameter("rackId");
        String storageId = request.getParameter("storageId");
        String type = request.getParameter("type");


        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("storageId", storageId);

        map.put("keyword", keyword);
        map.put("type", type);

        map.put("rackId", rackId);
        if (StringUtils.isNotBlank(size)) {
            map.put("current", current);
            map.put("pageSize", size);
            return service.getStockList(map);
        } else {
            return SingleResult.success(service.getStockListAll(map));
        }
    }

    @UserSessionRequired
    @PutMapping("/distributeStockBatch")
    @ApiOperation(value = "分配库存", notes = "分配库存")
    public SingleResult distributeStockBatch(@RequestBody @Validated List<DistributeStockReq> req) {
        Long userId = getCurrentUserId();
        service.distributeStockBatch(req, userId, getCompanyId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @PutMapping("/distributeStock")
    @ApiOperation(value = "分配库存", notes = "分配库存")
    public SingleResult distributeStock(@RequestBody @Validated DistributeStockReq req) {
        Long userId = getCurrentUserId();
        service.distributeStock(req, userId, getCompanyId());
        return SingleResult.success("");
    }


    @UserSessionRequired
    @PutMapping("/distributeStore")
    @ApiOperation(value = "配货区调货", notes = "配货区调货")
    public SingleResult distributeStore(@RequestBody @Validated DistributeStoreReq req) {
        Long userId = getCurrentUserId();
        service.distributeStore(req, getCompanyId(), userId);
        return SingleResult.success("");
    }


    @UserSessionRequired
    @PostMapping("/importDistributeStock")
    @ApiOperation(value = "导入分配库存", notes = "导入分配库存")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = DistributeStockImportRes.class))
    public SingleResult importDistributeStock(MultipartFile file, Long fromStorageId, Long fromRackId) {
        Long userId = getCurrentUserId();
        return service.importDistributeStock(file, fromStorageId, fromRackId, userId, getCompanyId());
    }

    @UserSessionRequired
    @PutMapping("/updateStockBatch")
    @ApiOperation(value = "批量更新库存", notes = "批量更新库存")
    public SingleResult updateStockBatch(@RequestBody @Validated List<UpdateStockReq> reqs) {
        Long userId = getCurrentUserId();
        service.updateStockBatch(reqs, userId, getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @PutMapping("/updateStock")
    @ApiOperation(value = "更新库存", notes = "更新库存")
    public SingleResult updateStock(@RequestBody @Validated UpdateStockReq req) {
        Long userId = getCurrentUserId();
        service.updateStock(req, userId, getCompanyId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @PutMapping("/doneApply")
    @ApiOperation(value = "盘点完成", notes = "盘点完成")
    public SingleResult doneApply(@RequestBody @Validated DoneUpdateStockReq req) {
        Long userId = getCurrentUserId();
        service.doneApply(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/applyUpdateStock")
    @ApiOperation(value = "申请盘点", notes = "申请盘点")
    public SingleResult applyUpdateStock(@RequestBody @Validated UpdateStockReq req) {
        Long userId = getCurrentUserId();
        service.applyUpdateStock(req, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/confirmApply")
    @ApiOperation(value = "申请盘点 确认", notes = "申请盘点 确认")
    public SingleResult confirmApply(Long id) {
        Long userId = getCurrentUserId();
        service.confirmApply(id, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("getFlowingList")
    @ApiOperation(value = "查看库存流水", notes = "查看库存流水")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rackId", value = "库位id"),
            @ApiImplicitParam(name = "keyword", value = "关键词"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "from", value = "库位流水 StorageLocation"),
            @ApiImplicitParam(name = "status", value = "状态 done"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "type", value = "库存流水类型 rackUpdate(盘盈盘亏)"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),
            @ApiImplicitParam(name = "current", value = "当前页"),
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = StockFlowingDto.class))
    public SingleResult getFlowingList(HttpServletRequest request) {
//        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();

        String rackId = request.getParameter("rackId");
        String type = request.getParameter("type");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        String keyword = request.getParameter("keyword");
        String status = request.getParameter("status");
        String from = request.getParameter("from");

        map.put("type", type);
        map.put("endTime", endTime);
        map.put("beginTime", beginTime);
        map.put("keyword", keyword);
        map.put("status", status);
        map.put("from", from);

        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
//        if (companyId != null) {
//            map.put("companyId", companyId +"");
//        }
        map.put("storageId", storageId);
        map.put("current", current);
        map.put("pageSize", size);
        if (!"default".equals(rackId)) {
            map.put("rackId", rackId);
        }
        return SingleResult.success("查询成功", service.getFlowing(map));
    }


    @UserSessionRequired
    @GetMapping("/getProductList")
    @ApiOperation(value = "获取商品列表", notes = "获取商品列表")
    public SingleResult getProductList(String keyword, Long rackId, Long productId,Long storageId) {
//        Long companyId = getCompanyId();
        return SingleResult.success("查询成功", service.getProductList(keyword, rackId, storageId, productId, null, 1));
    }
}

